package bid.yanhj.springboot.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import bid.yanhj.springboot.po.User;
import bid.yanhj.springboot.service.UsersService;

@Controller
@RequestMapping("/users")
public class UsersController {

    @Autowired
    private UsersService usersService;

    /**
     * rest 风格
     * 
     * @param page
     * @return
     */
    @RequestMapping("/{page}")
    public String showPage(@PathVariable String page,@ModelAttribute("aa") User user) {
        return page;
    }

    /**
     * 添加用户
     */
    @RequestMapping("/addUser")
    public String addUser(@ModelAttribute("aa") @Valid User user, BindingResult result) {
        if(result.hasErrors()) {
            return "input";
        }
        this.usersService.addUser(user);
        return "ok";
    }

    /**
     * 查询全部用户
     */
    @RequestMapping("/findUserAll")
    public String findUserAll(Model model) {
        List<User> list = this.usersService.findUserAll();
        model.addAttribute("list", list);
        return "showUsers";
    }

    @RequestMapping("/findUserById")
    public String findUserById(Integer userId, Model model) {
        User user = this.usersService.findUserById(userId);
        model.addAttribute("user", user);
        return "updateUser";
    }

    @RequestMapping("/editUser")
    public String editUser(User users) {
        this.usersService.updateUser(users);
        return "ok";
    }
    /**
     * 删除用户
     */
    @RequestMapping("/delUser")
    public String delUser(Integer userId){
        this.usersService.deleteUserById(userId);
        return "redirect:/users/findUserAll";
    }
}
